const sqlite3 = require('sqlite3').verbose();

// 创建数据库连接
const db = new sqlite3.Database('./factory.db', (err) => {
  if (err) {
    console.error('数据库连接错误:', err.message);
  } else {
    console.log('已连接到SQLite数据库');
  }
});

// 初始化数据库表
db.serialize(() => {
  // 事件表（合并两个项目的需求）
  db.run(`
    CREATE TABLE IF NOT EXISTS events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title TEXT NOT NULL,
      description TEXT,
      status TEXT CHECK(status IN ('pending', 'acknowledged', 'resolved')) DEFAULT 'pending',
      severity TEXT CHECK(severity IN ('low', 'medium', 'high', 'critical')),
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME,
      resolved_by INTEGER,
      acknowledged_by INTEGER,
      acknowledgement_time DATETIME,
      resolution_time DATETIME
    )
  `);
  // 添加索引以提高查询性能
  db.run("CREATE INDEX IF NOT EXISTS idx_events_status ON events(status)");
  db.run("CREATE INDEX IF NOT EXISTS idx_events_created ON events(created_at)");
  db.run("CREATE INDEX IF NOT EXISTS idx_events_severity ON events(severity)");
  
  console.log('数据库表初始化完成');
});

module.exports = db;